//
//  BaseModel.m
//  LBBase
//
//  Created by Gary on 15/7/1.
//  Copyright (c) 2015年 Lebo. All rights reserved.
//

#import "BaseModel.h"
#import "objc/runtime.h"
#import "ConfigDefine.h"

@implementation BaseModel

- (instancetype)init {
    self = [super init];
    if (self) {
        self._id = kBaseModelIdDefault;
    }
    return self;
}

+ (NSString *)tableName {
    return nil;
}

static NSDictionary *propertyDictionary;

+ (NSDictionary *)propertyDictionary {
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        AddProperty(kBaseModelPropertyId,   PDTLongLong,    kBaseModelTableColumnId);
        
        /*
         AddProperty(@"extend1", PDTString, @"extend1");
         AddProperty(@"extend2", PDTString, @"extend2");
         AddProperty(@"extend3", PDTString, @"extend3");
         AddProperty(@"extend4", PDTString, @"extend4");
         */
        propertyDictionary = [NSDictionary dictionaryWithDictionary:dic];
    });
    
    return propertyDictionary;
}

+ (NSString *)sql {
    NSLog(@"you must implement this method (sql) your self: %@", NSStringFromClass(self.class));
    return nil;
}

- (NSDictionary *)dictionaryOfPropertyAndValue {
    return [BaseModel dictionaryOfpropertyAndValueWithClass:self deep:1];
}

- (id)copyWithZone:(NSZone *)zone {
    id copy = [[[self class] alloc] init];
    
    if (copy) {
        [copy set_id:self._id];
        
        /*
        [copy setExtend1:self.extend1];
        [copy setExtend2:self.extend2];
        [copy setExtend3:self.extend3];
        [copy setExtend4:self.extend4];
         */
    }
    
    return copy;
}

/**
 * @brief 根据类的属性和值类型创建字典
 *
 * @param [in]
 * @param [out]
 * @return
 * @note
 */
+ (NSDictionary *)dictionaryOfpropertyAndValueWithClass:(BaseModel *)model deep:(int)deep {
    NSMutableDictionary *props = [NSMutableDictionary dictionary];
    Class c = model.class;
    while (deep-- > 0) {
        unsigned int outCount;
        objc_property_t *properties = class_copyPropertyList(c, &outCount);
        for (unsigned int i = 0; i<outCount; i++) {
            objc_property_t property = properties[i];
            const char *char_f = property_getName(property);
            NSString *propertyName = [NSString stringWithUTF8String:char_f];
            if (![props objectForKey:propertyName]) {
                id propertyValue = [model valueForKey:propertyName];
                if (propertyValue) {
                    [props setObject:propertyValue forKey:propertyName];
                }
                else {
                    [props setObject:[NSNull null] forKey:propertyName];
                }
            }
        }
        c = class_getSuperclass(c);
        free(properties);
    }
    
    return props;
}

@end
